import axios from 'axios'
import store from '@/store'
import router from '@/router'

// 1. 创建axios和基本配置
const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net/',
  timeout: 5000
})

// 2. 请求拦截器
instance.interceptors.request.use(config => {
  const { profile } = store.state.user
  if (profile.token) {
    config.headers.Authorization = `Bearer ${profile.token}`
  }
  return config
}, err => {
  return Promise.reject(err)
})

// 3. 响应拦截器
instance.interceptors.response.use(response => {
  return response.data
}, err => {
  if (err.response && err.response.status === 401) {
    // 清除用户信息
    store.commit('user/setProfile', {})
    // 跳转登录页
    router.push('/login')
  }
  return Promise.reject(err)
})

export default instance
